<template>
  <el-dialog width="400px" :title="editInfo.type == 'add' ? '添加' : '编辑'" :visible="isShow" :close-on-click-modal=false
    :close-on-press-escape=false @close="isShow && closeModal()">
    <Form ref="dataSourceForm" />
    <div slot="footer" class="dialog-footer">
      <el-button @click="closeModal">取 消</el-button>
      <el-button type="primary" @click="submitForm" :loading="isSubmiting">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { Vue, Component, Watch } from 'vue-property-decorator'
import { mapState, mapMutations, mapActions } from 'vuex'
import vuex, { actionsTypes } from '@/store/index'
import store from './store'
import Form from './Form'

vuex.registerModule(['modals', 'EditDataSourceModal'], store)

@Component({
  components: {
    Form
  },
  computed: {
    ...mapState('EditDataSourceModal', {
      isShow: state => state.isShow,
      form: state => state.form,
      editInfo: state => state.editInfo,
      callback: state => state.callback,
    })
  },
  methods: {
    ...mapMutations('EditDataSourceModal', {
      hideModal: actionsTypes.HIDE_MODAL,
      setModalForm: actionsTypes.SET_MODAL_FORM,
      resetModal: actionsTypes.RESET_MODAL_FORM,
    }),
    ...mapActions({
      setDataSource: 'SET_DATA_SOURCE',
      updateDataSource: 'UPDATE_DATA_SOURCE',
    }),
  }
})
export default class DataSourceDialog extends Vue {
  formLabelWidth = '120px'
  isSubmiting = false

  async submitForm() {
    try {
      const checked = await this.checkForm()
      if (!checked) {
        this.isSubmiting = false
        return
      }

      this.editDataSource()
    } catch (err) {
      console.log(err)
    } finally {
      this.callback({ finished: true })
    }
  }

  async editDataSource() {
    try {
      this.isSubmiting = true
      const params = this.getParams()
      let res = null
      if (this.editInfo.type == 'add') {
        res = await this.setDataSource(params) // 新增
      } else {
        res = await this.updateDataSource({ id: this.editInfo.id, params }) // 编辑
      }
      if (res.code == 100000) {
        this.msgSuccess('操作成功')
        this.successExecute()
      }
      // this.checkResCode(res.code, this.successExecute)
    } catch (e) {
      console.log(e)
    } finally {
      this.isSubmiting = false
    }
  }
  successExecute() {
    this.hideModal()
    this.$emit('getList')
  }

  async checkForm() {
    try {
      // 需要校验form表单
      return await this.$refs.dataSourceForm.checkForm()
    } catch (err) {
      console.log(err)
    }
  }

  getParams() {
    return this.$refs.dataSourceForm.getParams()
  }

  @Watch('isShow')
  onDialogShow(newVal, oldVal) {
    // 关闭弹窗时，重置弹窗信息
    if (!newVal && oldVal) {
      setTimeout(() => {
        this.resetModal()
      }, 500)
    }
  }

  // 关闭弹窗
  closeModal() {
    this.hideModal()
  }
}

</script>
